package by.ostrovsky.webhousingsystem.controller.validation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;

import by.ostrovsky.webhousingsystem.bean.user.RegistrationAction;
import by.ostrovsky.webhousingsystem.controller.ICheckController;
import by.ostrovsky.webhousingsystem.exception.CommonException;
import by.ostrovsky.webhousingsystem.exception.OperationErrorException;

public class CheckForNullFormFieldsController implements ICheckController<RegistrationAction, Boolean>{
	private static Logger logger = Logger.getLogger(CheckForNullFormFieldsController.class);
	
	@Override
	public Boolean check(RegistrationAction form) throws CommonException {
		
		Method[] methods = form.getClass().getDeclaredMethods();
		boolean isNull = false;
		
		for(Method m: methods){
			if(m.getName().startsWith("get")){
				try {
					Object varargs[] = null;
					isNull = m.invoke(form, varargs).equals("");
				}
				catch(NullPointerException e){
					return false;
				}
				catch (IllegalAccessException | IllegalArgumentException
						| InvocationTargetException e) {
					logger.error(e);
					throw new OperationErrorException();
				}
				if(isNull)
					return false;
			}
		}
		return true;
	}
}
